package com.difsonapps.android.joinme;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import com.difsonapps.android.joinme.R;
import com.google.gson.GsonBuilder;

import android.accounts.AccountAuthenticatorActivity;
import android.accounts.Account;  
import android.accounts.AccountAuthenticatorActivity;  
import android.accounts.AccountAuthenticatorResponse;
import android.accounts.AccountManager; 
import android.content.ContentResolver;  
import android.content.Context;
import android.content.DialogInterface;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


import android.widget.Toast;



 
public class RegisterActivity extends AccountAuthenticatorActivity {
    static final String TAG = LogConfig.getLogTag(RegisterActivity.class);
    // whether DEBUG level logging is enabled (whether globally, or explicitly
    // for this log tag)
    static final boolean DEBUG = LogConfig.isDebug(TAG);
    // whether VERBOSE level logging is enabled
    static final boolean VERBOSE = LogConfig.VERBOSE;

private AccountManager mAccountManager;
private Thread mAuthThread;
private String mAuthtoken;
private String mAuthtokenType;

/**
 * If set we are just checking that the user knows their credentials; this
 * doesn't cause the user's password to be changed on the device.
 */
private Boolean mConfirmCredentials = false;

/** for posting authentication attempts back to UI thread */
private final Handler mHandler = new Handler();
private TextView mMessage;
private String mPassword;
private EditText mPasswordEdit;
private EditText mUsernameEdit;

/** Was the original caller asking for an entirely new account? */
protected boolean mRequestNewAccount = false;

private static String mUsername;


public static String getUserName(){
    return (mUsername);
	}
    
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        mAccountManager = AccountManager.get(this);
        final Intent intent = getIntent();
        mUsername = intent.getStringExtra(Constants.PARAM_USERNAME);
        mAuthtokenType = intent.getStringExtra(Constants.PARAM_AUTHTOKEN_TYPE);
        mRequestNewAccount = mUsername == null;
        mConfirmCredentials = intent.getBooleanExtra(Constants.PARAM_CONFIRMCREDENTIALS, false);
        if ( DEBUG ) Log.d(TAG, "    request new: " + mRequestNewAccount);
//        requestWindowFeature(Window.FEATURE_LEFT_ICON);

        setContentView(R.layout.register_page);    
       // getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
        //android.R.drawable.ic_dialog_alert);

//        mMessage = (TextView) findViewById(R.id.login_message);
        mUsernameEdit = (EditText) findViewById(R.id.etEmail);
        mPasswordEdit = (EditText) findViewById(R.id.etPassword);

        mUsernameEdit.setText(mUsername);
       // mMessage.setText(getMessage());
        
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage( "Login_authenticating");//getText(R.string.login_authenticating));
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
            public void onCancel(DialogInterface dialog) {
                if ( DEBUG ) Log.d(TAG, "dialog cancel has been invoked");
                if (mAuthThread != null) {
                    mAuthThread.interrupt();
                    finish();
                }
            }
        });
        return dialog;
    }

    public void handleLogin(View view) {
//        if (mRequestNewAccount) {
//            mUsername = mUsernameEdit.getText().toString();
//        }
//        mPassword = mPasswordEdit.getText().toString();
//        if (TextUtils.isEmpty(mUsername) || TextUtils.isEmpty(mPassword)) {
//            mMessage.setVisibility(View.VISIBLE);
//            mMessage.setText(getMessage());
//        } else {
//            showProgress();
//            mMessage.setVisibility(View.GONE);
//            // Start authenticating...
//            mAuthThread =
//                KohaAuthHandler.attemptAuth(mUsername, mPassword, mHandler,
//                    AuthenticatorActivity.this);
//        }
    	mUsername = mUsernameEdit.getText().toString();
    	mPassword = mPasswordEdit.getText().toString();
    	//onAuthenticationResult("Auth_OK");
    	
    	try {
			loginAuth();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    
    public void loginAuth() throws JSONException{
    	try {
    		
       		List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    		urlParameters.add(new BasicNameValuePair("email", mUsername));
    		urlParameters.add(new BasicNameValuePair("password", mPassword));
    		urlParameters.add(new BasicNameValuePair("firstname", "Mhamad"));
    		urlParameters.add(new BasicNameValuePair("lastname",  "Badran"));
    		urlParameters.add(new BasicNameValuePair("name", null));
    		urlParameters.add(new BasicNameValuePair("phone", "06123456"));
    		urlParameters.add(new BasicNameValuePair("address",  "56 rue Tolbiac"));
    		urlParameters.add(new BasicNameValuePair("language", "fr_FR"));

		    String response = makeRequest("http://goovemail.com:28080/joinme/rest/user/postall", urlParameters);
    		Log.e(TAG, " Vous etes la 3 " );
    		

//		    if( response == null)
//		    	{
//		    	Toast.makeText(this, "You entered the auth!", Toast.LENGTH_LONG).show();
//		    	
//		    	}
//		    else{
//		    	jsonObject = new JSONObject(response);
//		    }
		    
		    
//    		JSONObject dato = new JSONObject();
//            Toast.makeText(this, "You entered the auth!", Toast.LENGTH_LONG).show();
//    		String Returned;
//            HttpClient httpclient = new DefaultHttpClient();
//            HttpPost post = new HttpPost("http://goovemail.com:28080/joinme/rest/login");
//            
//            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters);
//            post.setEntity(formEntity);
//            
//            HttpResponse response = httpclient.execute(post);
//            HttpEntity entity = response.getEntity();
//            Returned = EntityUtils.toString(entity);
//            Toast.makeText(this, Returned, Toast.LENGTH_LONG).show();
          } catch ( Exception ioe ) {
           ioe.printStackTrace();
          }
    }
    
    public  String makeRequest(String uri, List<NameValuePair> urlParameters) {
        try {
        	
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setEntity(new UrlEncodedFormEntity(urlParameters));
            HttpAsyncTask ttTask = new HttpAsyncTask();
            ttTask.execute(httpPost);

           return ttTask.result;
   
        } catch (Exception e) {
        	 Log.e(TAG, e.getMessage(), e.fillInStackTrace());
        }
        return null;
    }
    
    
    
    private class HttpAsyncTask extends AsyncTask<HttpUriRequest, Void, String> {
    	String result= null;;
    	@Override
        protected String doInBackground(HttpUriRequest... urls) {
    		BufferedReader reader=null;
            try {
            	HttpResponse response=  new DefaultHttpClient().execute(urls[0]);
            	InputStream is= response.getEntity().getContent();
            	 if(is!=null)
            	 {
            		 reader = new BufferedReader(new InputStreamReader(is));
                     StringBuilder sb = new StringBuilder();
                     String line = null;
                     while((line = reader.readLine()) != null)
                     {
                            sb.append(line + "\n");
                     }              
                     result = sb.toString();
            	 }
            	 Log.d(TAG, "HttpAsyncTask passed succesfully");
            	  
			} catch (Exception e) {
			Log.e(TAG, e.getMessage(), e);
			}   
            
            return result;
        }
        // onPostExecute displays the results of the AsyncTask.
        @Override
        protected void onPostExecute(String result) {
          	 Log.d(TAG, result);
    	
       }
    }
    
    
    
    /**
     * Called when response is received from the server for confirm credentials
     * request. See onAuthenticationResult(). Sets the
     * AccountAuthenticatorResult which is sent back to the caller.
     *
     * @param the confirmCredentials result.
     */
    protected void finishConfirmCredentials(boolean result) {
        if ( DEBUG ) Log.d(TAG, "finishConfirmCredentials()");
        final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);
        mAccountManager.setPassword(account, mPassword);
        Log.d(TAG,"Password: " + mAccountManager.getPassword(account));
        final Intent intent = new Intent();
        intent.putExtra(AccountManager.KEY_BOOLEAN_RESULT, result);
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        finish();
    }

    protected void finishLogin() {
        if ( DEBUG ) Log.d(TAG, "finishLogin()");
        final Account account = new Account(mUsername, Constants.ACCOUNT_TYPE);

        if (mRequestNewAccount) {
            mAccountManager.addAccountExplicitly(account, mPassword, null);
            // Set contacts sync for this account.
            //ContentResolver.setSyncAutomatically(account, ContactsContract.AUTHORITY, true);
        } else {
            mAccountManager.setPassword(account, mPassword);
        }
        
        Log.d(TAG,"Password: " + mAccountManager.getPassword(account));

        
        mAccountManager.setUserData(account, Constants.AUTH_SESSION_KEY, mAuthtoken);        
       
        final Intent intent = new Intent();
        mAuthtoken = mPassword;
        intent.putExtra(AccountManager.KEY_ACCOUNT_NAME, mUsername);
        intent
            .putExtra(AccountManager.KEY_ACCOUNT_TYPE, Constants.ACCOUNT_TYPE);
        if (mAuthtokenType != null
            && mAuthtokenType.equals(Constants.AUTHTOKEN_TYPE)) {
            intent.putExtra(AccountManager.KEY_AUTHTOKEN, mAuthtoken);
        }
        setAccountAuthenticatorResult(intent.getExtras());
        setResult(RESULT_OK, intent);
        finish();
    }

    
    /**
     * Called when the authentication process completes (see attemptLogin()).
     */
    public void onAuthenticationResult(String authToken) {
        if ( DEBUG ) Log.d(TAG, "onAuthenticationResult(" + authToken + ")");
        // Hide the progress dialog
       // hideProgress();
       
        mAuthtoken = authToken;
        if (authToken != null) {
            if (!mConfirmCredentials) {
                finishLogin();
                Toast.makeText(this, "Logged in", Toast.LENGTH_LONG).show();
//                InfoActivity.loginButton.setVisibility(View.GONE);
//                InfoActivity.userLoggedInTextView.setText(getResources().getString(R.string.user_logged) + " " + mUsername);
//                InfoActivity.userLoggedInTextView.setVisibility(View.VISIBLE);
//                InfoActivity.myBooksButton.setVisibility(View.VISIBLE);
            } else {
                finishConfirmCredentials(true);
            }
        } else {
            Log.e(TAG, "onAuthenticationResult: failed to authenticate");
            mMessage.setVisibility(View.VISIBLE);

               
               // Toast.makeText(this, KohaAuthHandler.auri, Toast.LENGTH_LONG).show();
            if (mRequestNewAccount) {
                // "Please enter a valid username/password.
                mMessage
                    .setText("Please Enter a valid userName/pass");//getText(R.string.auth_result_fail));
            } else {
                // "Please enter a valid password." (Used when the
                // account is already in the database but the password
                // doesn't work.)
                mMessage
                    .setText("Please enter a valid Password");//getText(R.string.auth_result_fail));
            }
        }
    }

    
    
	public void onRegisterClick(View v){
		handleLogin(v);
	}
    
    public void onLoginClick(View v){
    	finish();
  	
    }
    
    
    
    /*
    
        private void createAccount() {

            // Validation!

            new AsyncTask<String, Void, Intent>() {

               // String name = ((TextView) findViewById(R.id.etEmail)).getText().toString().trim();
                String accountName = ((TextView) findViewById(R.id.etEmail)).getText().toString().trim();
                String accountPassword = ((TextView) findViewById(R.id.etPassword)).getText().toString().trim();

                @Override
                protected Intent doInBackground(String... params) {

                    Log.d("Badran", TAG + "> Started authenticating");

                    String authtoken = null;
                    Bundle data = new Bundle();
                    try {
                        //authtoken = sServerAuthenticate.userSignUp(name, accountName, accountPassword, AccountGeneral.AUTHTOKEN_TYPE_FULL_ACCESS);
            
                        data.putString(AccountManager.KEY_ACCOUNT_NAME, accountName);
                        data.putString(AccountManager.KEY_ACCOUNT_TYPE,"TypoAccount");  //mAccountType);
                        data.putString(AccountManager.KEY_AUTHTOKEN, "auth.token");
                        data.putString(PARAM_USER_PASS, accountPassword);
                        
                        Log.d("Badran", TAG + "> Account created");
                        
                    } catch (Exception e) {
                        data.putString(KEY_ERROR_MESSAGE, e.getMessage());
                    }

                    final Intent res = new Intent();
                    res.putExtras(data);
                    return res;
                }

                @Override
                protected void onPostExecute(Intent intent) {
                    if (intent.hasExtra(KEY_ERROR_MESSAGE)) {
                        Toast.makeText(getBaseContext(), intent.getStringExtra(KEY_ERROR_MESSAGE), Toast.LENGTH_SHORT).show();
                    } else {
                        setResult(RESULT_OK, intent);
                        finish();
                    }
                }
            }.execute();
        }
        
  
*/
        

 
}